<template>
  <div class="main-div">
    <div class="searchSystem">
      <el-select
        v-model="orgName"
        filterable
        clearable
        placeholder="请选择机构"
        style="width: 300px;margin-right: 20px;border: 1px solid #DCDFE6;border-radius: 4px;height: 40px"
        collapse-tags
        @change="changeOrg"
      >
        <el-option
          v-for="item in orgNameList"
          :key="item.orgId"
          :label="item.orgName"
          :value="item.orgId"
        />
      </el-select>
      <el-date-picker
        v-model="createDateRange"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        value-format="yyyy-MM-dd"
        style="width: 400px"
      />
      <el-button type="primary" class="search-btn" @click="systemSearch">搜索</el-button>
    </div>
    <div class="main-table-div">
      <el-table
        ref="multipleTable"
        :data="sysList"
        tooltip-effect="dark"
        style="width: 100%;"
        height="calc(100vh - 330px)"
        @selection-change="selectData"
      >
        <el-table-column
          v-if="show"
          label="行号"
          type="logId"
        />
        <el-table-column
          label="行号"
          type="index"
          width="100"
        />
        <el-table-column
          prop="dates"
          label="备份时间"
          style="width: 25%"
        />
        <el-table-column
          prop="orgName"
          label="业务机构"
          style="width: 25%"
        />
        <el-table-column
          fixed="right"
          label="操作"
          width="120"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click.native.prevent="optionRow(scope.$index, sysList)"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination
        :current-page="currentPage4"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { getCurUserOrgList, getDataBackupList, downloadDataBackupFile } from '@/api/dataBackUp'
export default {
  name: 'System',
  data() {
    return {
      pickerOptions: {
        disabledDate(date) {
          // disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          if (date.getTime() < Date.now()) {
            return false
          } else {
            return true
          }
        },
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      show: false,
      orgNameList: [],
      orgName: '',
      orgId: '',
      createDateRange: '',
      startDate: '',
      endDate: '',
      sysList: [],
      downLoad: '下载',
      total: 0,
      pageNo: 1,
      pageSize: 10,
      currentPage4: 1
    }
  },
  watch: {
    createDateRange(time) {
      if (time) {
        this.startDate = time[0]
        this.endDate = time[1]
      } else {
        this.startDate = ''
        this.endDate = ''
      }
    }
  },
  created() {
    this.getOrgDoc()
    this.systemSearch()
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.systemSearch()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageNo = val
      this.systemSearch()
    },
    optionRow(index, rows) {
      console.log(rows[index].logId)
      const params = {
        logId: rows[index].logId
      }
      downloadDataBackupFile({ ...params }).then(res => {
        const blob = new Blob([res.data], { type: 'application/xml;charset=utf-8' })
        const href = window.URL.createObjectURL(blob)
        if (window.navigator.msSaveBlob) {
          try {
            const patt = new RegExp('fileName=([^;]+\\.[^\\.;]+);*')
            const reg = /^["](.*)["]$/g
            const contentDisposition = res.headers['content-disposition']
            const result = patt.exec(contentDisposition)
            const filename = result[1]
            window.navigator.msSaveBlob(blob, decodeURI(filename.replace(reg, '$1')))
          } catch (e) {
            console.log(e)
          }
        } else {
          const patt = new RegExp('fileName=([^;]+\\.[^\\.;]+);*')
          const reg = /^["](.*)["]$/g
          const contentDisposition = res.headers['content-disposition']
          const result = patt.exec(contentDisposition)
          const filename = result[1]
          const downloadElement = document.createElement('a')

          downloadElement.download = decodeURI(filename.replace(reg, '$1'))
          downloadElement.style.display = 'none'
          downloadElement.href = href
          document.body.appendChild(downloadElement)
          downloadElement.click()
          document.body.removeChild(downloadElement)
          window.URL.revokeObjectURL(href)
        }
      }).finally(_ => {
        this.loading = false
      })
    },
    selectData(val) {
      this.sysList = val
    },
    getOrgDoc() {
      const params = {
      }
      getCurUserOrgList(params).then(res => {
        this.orgNameList = res.data
        console.log(this.orgNameList)
      })
        .finally(() => {
          this.loading = false
        })
    },
    systemSearch() {
      const params = {
        searchOrgId: this.orgId,
        startDate: this.startDate,
        endDate: this.endDate,
        pageNo: this.pageNo,
        pageSize: this.pageSize
      }
      getDataBackupList(params).then(res => {
        const data = res.data
        this.sysList = data.results
        this.total = data.totalRecord
        console.log(this.sysList)
      })
        .finally(() => {
          this.loading = false
        })
    },
    changeOrg(val) {
      this.orgId = ''
      this.orgName = ''
      let obj = {}
      obj = this.orgNameList.find((item) => {
        return item.orgId === val
      })
      if (obj != null) {
        this.orgName = obj.orgName
        this.orgId = obj.orgId
      } else {
        this.orgName = ''
        this.orgId = ''
      }
    }
  }
}
</script>

<style scoped>
  .main-div{
    width: 100%;
    background-color: #ffffff;
  }
  .searchSystem {
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 10px;
    width: 100%;
    margin: 20px;
  }
  .search-btn{
    margin-left: 20px;
  }
  .main-table{
    width: 100%;
    height: 100%;
  }
</style>
